/*
 * Copyright 2014 Graham Smith
 */
package uk.co.wobblycogs.vegas.scan;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.CONTINUE;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Graham Smith
 */
public abstract class FileFinder extends SimpleFileVisitor<Path> {

	protected static final Logger logger = LoggerFactory.getLogger(FileFinder.class);
	private final PathMatcher matcher;

	public FileFinder(String pattern) {
		matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
		Path name = file.getFileName();
		if (name != null && matcher.matches(name)) {
			//logger.debug("Found: {}", file);
			try {
				process(file);
			} catch (IOException ioe) {
				logger.debug("Failed while processing file: " + file, ioe);
			}
		}
		return CONTINUE;
	}

	public abstract void process(Path file) throws IOException;

	@Override
	public FileVisitResult visitFileFailed(Path file, IOException ioe) {
		logger.debug("Failed to visit: " + file, ioe);
		return CONTINUE;
	}
}
